package com.ly.anno;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/11/3
 * Email haijunzhou@hnit.edu.cn
 */
public class ClassDemo {

    public static void main(String[] args)
            throws NoSuchMethodException,
            InvocationTargetException,
            IllegalAccessException {
        A a = new A();
        A b = new B();

        // 不通过反射调用 a 方法, 看报错
        // a.callTest("张三");

        showObject(a);
        System.out.println("-------------------");
        showObject(b);
    }

    public static void showObject(Object object) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class<?> aClass = object.getClass();
        System.out.println("aClass.getName() = " + aClass.getName());
        System.out.println("aClass.getSimpleName() = " + aClass.getSimpleName());
        // 共有的属性
        for (Field field : aClass.getFields()) {
            System.out.println("field = " + field);
        }
        // 定义的属性
        for (Field declaredField : aClass.getDeclaredFields()) {
            System.out.println("declaredField = " + declaredField);
        }

        Method test = aClass.getDeclaredMethod("test", String.class);
        if(test != null){
            // 设置强制访问 不会产生 IllegalAccessException 了
            test.setAccessible(true);
            test.invoke(object, "张三");
        }
    }
}

class A {
    private int a;
    String b;
    protected Byte c;
    public Date d ;

    public int getA(){
        return a;
    }

    public void callTest(String s){
        test(s);
    }

    private void test(String s){
        int i = 1/0;
        System.out.println("hello " + s);
    }
}

class B extends A{

    @Override
    public void callTest(String s) {
        super.callTest(s);
    }
}